package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.myapplication.db.room.dao.CalculationParametersDao;
import com.example.myapplication.db.room.dao.MyAppDatabase;
import com.example.myapplication.db.room.entity.CalculationParameters;
import com.google.android.material.textfield.TextInputEditText;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private MyAppDatabase mDatabase;

    public void setmDatabase(MyAppDatabase mDatabase) {
        this.mDatabase = mDatabase;
    }

    @SuppressLint({"MissingInflatedId", "SetTextI18n"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        获取数据库实例
//        MyAppDatabase db = Room.databaseBuilder(this, MyAppDatabase.class, "my-database-name")
//                .allowMainThreadQueries()
//                .fallbackToDestructiveMigration()
//                .fallbackToDestructiveMigrationOnDowngrade()
//                .build();

        MyAppDatabase db = MyAppDatabase.getInstance(this);
        CalculationParametersDao calculationParametersDao = db.calculationParametersDao();

        super.onCreate(savedInstanceState);

//        FlowManager.init(this);
        setContentView(R.layout.activity_main);
        CalculationParameters calculationParameters = new CalculationParameters();
        Button startButton = findViewById(R.id.startDateTimeButton);
        Button endButton = findViewById(R.id.endDateTimeButton);
        Button startJisuanButton = findViewById(R.id.startJisuanButton);
        Button btnToggleTime = findViewById(R.id.btnToggleTime);

        TextView startTextView = findViewById(R.id.startDateTimeTextView);
        TextView endTextView = findViewById(R.id.endDateTimeTextView);

        TextView timeValue                  = findViewById(R.id.intervalTimeValueTextView);
        TextView amountValue                = findViewById(R.id.calculatedAmountValueTextView);
        TextView intervalMinutesTextView    = findViewById(R.id.intervalMinutesValueTextView);

        TextInputEditText hourlyRateEditText = findViewById(R.id.hourlyRateEditText);

        startButton.setOnClickListener(v -> {
//点击确定后将 timeValue amountValue intervalMinutesTextView 置为空 传给mergeDialog 方法处理
            mergeDialog(s -> {

                calculationParameters.setStartTime(DateUtil.parse(s, DatePattern.NORM_DATETIME_PATTERN));
                startTextView.setText(s);
            },startTextView,timeValue,amountValue,intervalMinutesTextView);
        });

        endButton.setOnClickListener(v -> {
            mergeDialog(s -> {
                calculationParameters.setEndTime(DateUtil.parse(s, DatePattern.NORM_DATETIME_PATTERN));
                endTextView.setText(s);
            },endTextView,timeValue,amountValue,intervalMinutesTextView);
        });
        startJisuanButton.setOnClickListener(v -> {
            String string = hourlyRateEditText.getText().toString();
            if (string.isEmpty()){
                gettoast();
                return;
            }
            BigDecimal divide = new BigDecimal(string).divide(new BigDecimal(60),5, RoundingMode.UP);

            if (calculationParameters.getStartTime() != null && calculationParameters.getEndTime() != null) {
                long diffInMs = DateUtil.betweenMs(calculationParameters.getStartTime(), calculationParameters.getEndTime());

                long hours = diffInMs / DateUnit.HOUR.getMillis(); // 1小时 = 1000 * 60 * 60 毫秒
                long minutes = (diffInMs % DateUnit.HOUR.getMillis()) / DateUnit.MINUTE.getMillis(); // 1分钟 = 1000 * 60 毫秒
                long seconds = (diffInMs % DateUnit.MINUTE.getMillis()) / DateUnit.SECOND.getMillis(); // 1秒 = 1000 毫秒

                String format = String.format("%d小时%d分钟%d秒", hours, minutes, seconds);
                timeValue.setText(format);
                timeValue.setVisibility(View.VISIBLE);
                System.out.println("计算完成   " + format);

                // 全部转换为分钟
                long intervalMinutes =   diffInMs / DateUnit.MINUTE.getMillis();
                BigDecimal amount = divide.multiply(new BigDecimal(intervalMinutes));
                System.out.println("所需金额   " + amount);
                amountValue.setText(amount.toString());
                amountValue.setVisibility(View.VISIBLE);
                intervalMinutesTextView.setText(String.valueOf(intervalMinutes));
                intervalMinutesTextView.setVisibility(View.VISIBLE);

                calculationParameters.setIntervalMinutes(intervalMinutes);
                calculationParameters.setAmount(amount);
                calculationParameters.setHours(hours);
                calculationParameters.setMinutes(minutes);
                calculationParameters.setSeconds(seconds);
                calculationParameters.setIntervalTime(diffInMs);
                calculationParametersDao.insert(calculationParameters);
                List<CalculationParameters> all = calculationParametersDao.getAll();
//                FlowManager.init(new FlowConfig.Builder(this).build());
//                long insert = calculationParameters.insert();
//                List<CalculationParameters> all = SQLite.select().from(CalculationParameters.class).queryList();
                String jsonString = JSONObject.toJSONString(calculationParameters);
                System.out.println("添加了 行数据 添加的是"+ jsonString);
                System.out.println("获取到所有的计算参数是"+ JSONObject.toJSONString(all));


            }
        });

        btnToggleTime.setOnClickListener(v -> {
//       如果endTextView 的值不为空的时候 将endTextView的值赋值给startTextView 不管怎么样都将endTextView的值置为空
            if (!StrUtil.isEmpty(endTextView.getText().toString())){
                startTextView.setText(endTextView.getText().toString());
            }else {

                startTextView.setText("");
            }
            endTextView.setText("");
        });

        Button viewHistoryButton = findViewById(R.id.historyButton);

        viewHistoryButton.setOnClickListener(v->{

                // 创建Intent对象，指定要跳转到的目标页面
                Intent intent = new Intent(MainActivity.this, HistoryActivity.class);

                // 如果需要传递数据到目标页面，可以使用putExtra()方法
                // intent.putExtra("key", value);
                // 启动目标页面
                startActivity(intent);

        });
    }

    private void gettoast() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("请输入一小时所需金额！");
        builder.setPositiveButton("确认",  new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取TextInputEditText控件
                TextInputEditText hourlyWageInput = findViewById(R.id.hourlyRateEditText);

                // 将焦点转移至TextInputEditText
                hourlyWageInput.requestFocus();

                // 可选：显示软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(hourlyWageInput, InputMethodManager.SHOW_IMPLICIT);
            }
        });
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();

        // 设置对话框居中显示（可能需要自定义主题或布局）
        WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
    }

    @Override
    public void onClick(View v) {


    }




    public void merge() {
        Button oplantime = findViewById(R.id.confirm_button);
        //点击"时间"按钮布局 设置时间
        oplantime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mergeDialog(s -> {
                    oplantime.setText(s);
                },null,null,null,null);
            }
        });
    }

    private void mergeDialog(CustomDatePickerDialogListener listener,TextView textView,TextView timeValue,TextView amountValue,TextView intervalMinutesTextView) {
        //自定义控件
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.custom_date_time_picker_dialog, null);
        final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
        Calendar calendar = Calendar.getInstance();
        if (textView!= null){
            String dataStr = textView.getText().toString();
            if (StrUtil.isNotBlank(dataStr)){
                calendar  =DateUtil.parse(dataStr, DatePattern.NORM_DATETIME_PATTERN).toCalendar();
            }
        }


        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));

        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);

        //初始化当前日期
//        calendar.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), null);


        //设置date布局
        builder.setView(view);
        builder.setTitle("设置日期时间信息");


        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            int mHour, mMinute;

            @Override
            public void onClick(DialogInterface dialog, int which) {
                mHour = timePicker.getCurrentHour();
                mMinute = timePicker.getCurrentMinute();
                //时间小于10的数字 前面补0 如01:12:00
                StringBuilder append = new StringBuilder().append(mHour < 10 ? "0" + mHour : mHour).append(":")
                        .append(mMinute < 10 ? "0" + mMinute : mMinute).append(":00");

                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));

                listener.onDateSelected(sb.append(" ").append(append).toString());
                timeValue.setText("");
                amountValue.setText("");
                intervalMinutesTextView.setText("");

                dialog.cancel();

            }
        });
        builder.setNegativeButton("取  消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }

    public interface CustomDatePickerDialogListener {
        void onDateSelected(String time);
    }



}